#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git初始化和上传到Gitee的脚本

使用说明：
1. 确保已安装Git并配置了用户信息
2. 在Gitee上创建一个新的仓库
3. 修改脚本中的GITEE_REPO_URL为你的仓库地址
4. 运行脚本：python upload_to_gitee.py
"""

import os
import subprocess
import sys
from pathlib import Path

# 配置信息 - 请根据实际情况修改
GITEE_REPO_URL = "https://gitee.com/liuxnstandy57/api-interface-testing.git"  # 替换为你的Gitee仓库地址
COMMIT_MESSAGE = "Initial commit: API自动化测试项目"
BRANCH_NAME = "main"

def run_command(command, cwd=None):
    """
    执行命令并返回结果
    """
    try:
        print(f"执行命令: {command}")
        result = subprocess.run(
            command,
            shell=True,
            cwd=cwd,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )
        
        if result.stdout:
            print(f"输出: {result.stdout.strip()}")
        
        if result.stderr and result.returncode != 0:
            print(f"错误: {result.stderr.strip()}")
            return False, result.stderr
        
        return True, result.stdout
    
    except Exception as e:
        print(f"命令执行异常: {e}")
        return False, str(e)

def check_git_installed():
    """
    检查Git是否已安装
    """
    success, _ = run_command("git --version")
    if not success:
        print("错误: Git未安装或未添加到PATH环境变量")
        print("请先安装Git: https://git-scm.com/downloads")
        return False
    return True

def check_git_config():
    """
    检查Git用户配置
    """
    success, output = run_command("git config --global user.name")
    if not success or not output.strip():
        print("警告: Git用户名未配置")
        print("请运行: git config --global user.name \"Your Name\"")
        return False
    
    success, output = run_command("git config --global user.email")
    if not success or not output.strip():
        print("警告: Git邮箱未配置")
        print("请运行: git config --global user.email \"your.email@example.com\"")
        return False
    
    return True

def init_git_repo(project_path):
    """
    初始化Git仓库
    """
    print("\n=== 初始化Git仓库 ===")
    
    # 检查是否已经是Git仓库
    git_dir = project_path / ".git"
    if git_dir.exists():
        print("Git仓库已存在，跳过初始化")
        return True
    
    # 初始化仓库
    success, _ = run_command("git init", cwd=project_path)
    if not success:
        print("Git仓库初始化失败")
        return False
    
    print("Git仓库初始化成功")
    return True

def add_and_commit(project_path):
    """
    添加文件并提交
    """
    print("\n=== 添加文件并提交 ===")
    
    # 添加所有文件
    success, _ = run_command("git add .", cwd=project_path)
    if not success:
        print("文件添加失败")
        return False
    
    # 检查是否有文件需要提交
    success, output = run_command("git status --porcelain", cwd=project_path)
    if not success:
        print("检查Git状态失败")
        return False
    
    if not output.strip():
        print("没有文件需要提交")
        return True
    
    # 提交文件
    success, _ = run_command(f'git commit -m "{COMMIT_MESSAGE}"', cwd=project_path)
    if not success:
        print("文件提交失败")
        return False
    
    print("文件提交成功")
    return True

def add_remote_and_push(project_path):
    """
    添加远程仓库并推送
    """
    print("\n=== 添加远程仓库并推送 ===")
    
    # 检查远程仓库是否已存在
    success, output = run_command("git remote -v", cwd=project_path)
    if success and "origin" in output:
        print("远程仓库已存在，移除旧的远程仓库")
        run_command("git remote remove origin", cwd=project_path)
    
    # 添加远程仓库
    success, _ = run_command(f"git remote add origin {GITEE_REPO_URL}", cwd=project_path)
    if not success:
        print("添加远程仓库失败")
        return False
    
    # 设置默认分支
    success, _ = run_command(f"git branch -M {BRANCH_NAME}", cwd=project_path)
    if not success:
        print("设置默认分支失败")
        return False
    
    # 推送到远程仓库
    print(f"推送到远程仓库: {GITEE_REPO_URL}")
    success, _ = run_command(f"git push -u origin {BRANCH_NAME}", cwd=project_path)
    if not success:
        print("推送失败，可能需要先在Gitee上创建仓库或检查权限")
        return False
    
    print("推送成功！")
    return True

def main():
    """
    主函数
    """
    print("=== API自动化测试项目上传到Gitee ===")
    print(f"目标仓库: {GITEE_REPO_URL}")
    
    # 获取项目路径
    project_path = Path(__file__).parent.absolute()
    print(f"项目路径: {project_path}")
    
    # 检查Git环境
    if not check_git_installed():
        return False
    
    if not check_git_config():
        print("\n请先配置Git用户信息后再运行此脚本")
        return False
    
    # 检查仓库URL配置
    if "your_username" in GITEE_REPO_URL or "your_repo_name" in GITEE_REPO_URL:
        print("\n错误: 请先修改脚本中的GITEE_REPO_URL为你的实际仓库地址")
        print("示例: https://gitee.com/your_username/api-test-project.git")
        return False
    
    # 执行Git操作
    steps = [
        ("初始化Git仓库", lambda: init_git_repo(project_path)),
        ("添加文件并提交", lambda: add_and_commit(project_path)),
        ("添加远程仓库并推送", lambda: add_remote_and_push(project_path))
    ]
    
    for step_name, step_func in steps:
        print(f"\n--- {step_name} ---")
        if not step_func():
            print(f"\n❌ {step_name}失败，上传中止")
            return False
        print(f"✅ {step_name}完成")
    
    print("\n🎉 项目已成功上传到Gitee！")
    print(f"仓库地址: {GITEE_REPO_URL}")
    
    return True

if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n用户中断操作")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n脚本执行异常: {e}")
        sys.exit(1)